package com.hfut.meilin.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hfut.meilin.entity.Employee;
import com.hfut.meilin.common.Result;
import com.hfut.meilin.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
/*
(1）注入的就是实现类，只不过拿接口来接收，接收的类型为接口，面向接口编程，那么为何要面向接口编程？
这就涉及到使用接口做代理，因为通过@autowired的对象是通过接口的方式会使用jdk动态代理，jdk动态代理只能对实现接口的类生成代理，而不能针对类。
(2）注入的是实现类对象，接收的是接口；理解为多态
 */
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登陆
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")    //用post方式请求的（按下登陆键）
    public Result<Employee> login(HttpServletRequest request, @RequestBody Employee employee){          //将Employee对象返回   @RequestBody里面装的是登陆用的 username和 keyword
                                                                                                        // HttpServletRequest将员工对象的id存到session中（随时获取登陆用户）
        //1.将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());     //sql等值查询
        Employee emp = employeeService.getOne(queryWrapper);              //getone是因为用户名是唯一的

        //3.如果没有查询到返回登陆失败结果
        if(emp == null){
            return Result.error("登陆失败");
        }
        //4.密码比对，如果不一致则返回登陆失败结果
        if(!emp.getPassword().equals(password)){
            return Result.error("登陆失败");
        }
        //5.查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(emp.getStatus() == 0){
            return Result.error("账号已禁用");
        }
        //6.登陆成功，将员工id存入Session并返回登陆成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return Result.success(emp);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return  Result.success("退出成功");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping    //employee路径已经在最前面加过了
    public Result<String> save(HttpServletRequest request, @RequestBody Employee employee){     //@RequestBody用来接收json形式的数据
        log.info("新增员工，员工信息:{}",employee.toString());
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());

        //获得当前登录用户的id
        //Long empId = (Long) request.getSession().getAttribute("employee");
        //employee.setCreateUser(empId);
        //employee.setUpdateUser(empId);

        employeeService.save(employee);    //mybaitsplus 的save方法，通过Service
        return Result.success("新增员工成功");
    }

    /**
     * 员工信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize, String name){     //url后面的page等信息直接接收
        log.info("page = {},pageSize = {},name = {}" ,page,pageSize,name);

        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //执行查询
        employeeService.page(pageInfo,queryWrapper);   //接收后,page里面自动改好

        return Result.success(pageInfo);
    }

    /**
     * 根据id修改员工信息
     * @param employee
     * @return
     */
    @PutMapping
    public Result<String> update(HttpServletRequest request,@RequestBody Employee employee){
        log.info(employee.toString());

        long id = Thread.currentThread().getId();
        log.info("线程id为:{}",id);
        // Long empId = (Long) request.getSession().getAttribute("employee");
       //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(empId);
        employeeService.updateById(employee);

        return Result.success("员工信息修改成功");
    }

    @GetMapping("/{id}")
    public Result<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        if(employee !=null){
            return Result.success(employee);
        }
        return Result.error("没有查询到对应员工信息");

    }

}
